package com.hxd.otc.widget;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.hxd.otc.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by kangxin on 2017/9/22.
 */

public class SearchView extends FrameLayout implements View.OnClickListener {

    @BindView(R.id.et_search)
    EditText mEtSearch;
    @BindView(R.id.iv_clear)
    ImageView mImageBtnClear;

    private OnSearchListener onSearchListener;

    private boolean mAutoSearch = false;

    public SearchView(Context context) {
        this(context, null);
    }

    public SearchView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SearchView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }


    private void initView(Context context) {
        LayoutInflater.from(context).inflate(R.layout.view_search, this);
        ButterKnife.bind(this);
        setTextChangeListner();
        setOnEditorActionListener();
    }

    /**
     * 监听文本
     */
    private void setTextChangeListner() {
        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                mImageBtnClear.setVisibility(TextUtils.isEmpty(s.toString()) ? GONE : VISIBLE);
                if (mAutoSearch && onSearchListener != null) {
                    onSearchListener.onSearch(s.toString());
                }
            }
        });
    }

    private void setOnEditorActionListener() {
        mEtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode()
                        && KeyEvent.ACTION_DOWN == event.getAction())) {
                    turnOffKeyboard();
                    if (onSearchListener != null) {
                        onSearchListener.onSearch(mEtSearch.getText().toString());
                    }
                    return true;
                }
                return false;
            }
        });
    }

    @OnClick({R.id.iv_clear})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_clear://清理数据
                mEtSearch.setText("");
                break;
        }
    }


    /**
     * @param hint 搜索框默认提示文本
     */
    public void setHint(String hint) {
        mEtSearch.setHint(hint);
    }

    /**
     * 是否自动搜索（随着内容变化回调搜索监听，默认开启）
     *
     * @param autoSearch
     */
    public void setAutoSearch(boolean autoSearch) {
        this.mAutoSearch = autoSearch;
    }

    public void setOnSearchListener(OnSearchListener onSearchListener) {
        this.onSearchListener = onSearchListener;
    }

    public interface OnSearchListener {
        void onSearch(String content);
    }

    public void turnOffKeyboard() {
        hideSoftKeyboard(mEtSearch);
    }

    private void hideSoftKeyboard(View view) {
        if (view == null)
            return;
        View focusView = null;
        if (view instanceof EditText)//判断view是否是EditText
            focusView = view;
        Context context = view.getContext();
        if (context != null && context instanceof Activity) {//context得是Activity
            Activity activity = ((Activity) context);
            focusView = activity.getCurrentFocus();//获取当前activity中获得焦点的view
        }

        if (focusView == null) return;//当前activity中有获得焦点的view，才进行掩藏软键盘
        if (focusView.isFocused()) {//取消获得焦点view的获取状态
            focusView.clearFocus();
        }
        //掩藏软键盘
        InputMethodManager manager = (InputMethodManager) focusView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (manager == null) return;
        manager.hideSoftInputFromWindow(focusView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        manager.hideSoftInputFromInputMethod(focusView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

    }
}
